package com.demo.demospringboot.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 日志拦截器
 */
@Component
public class LoggingInterceptor implements HandlerInterceptor {

  private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);
  private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String requestId = generateRequestId();
    LocalDateTime startTime = LocalDateTime.now();

    // 将请求ID和开始时间存储到请求属性中
    request.setAttribute("requestId", requestId);
    request.setAttribute("startTime", startTime);

    logger.info("[{}] HTTP请求开始 - {} {} - 客户端IP: {} - User-Agent: {}",
        requestId,
        request.getMethod(),
        request.getRequestURI(),
        getClientIpAddress(request),
        request.getHeader("User-Agent"));

    return true;
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
      throws Exception {
    String requestId = (String) request.getAttribute("requestId");
    LocalDateTime startTime = (LocalDateTime) request.getAttribute("startTime");
    LocalDateTime endTime = LocalDateTime.now();

    if (startTime != null) {
      long duration = java.time.Duration.between(startTime, endTime).toMillis();

      if (ex != null) {
        logger.error("[{}] HTTP请求异常 - {} {} - 状态码: {} - 耗时: {}ms - 异常: {}",
            requestId,
            request.getMethod(),
            request.getRequestURI(),
            response.getStatus(),
            duration,
            ex.getMessage());
      } else {
        logger.info("[{}] HTTP请求完成 - {} {} - 状态码: {} - 耗时: {}ms",
            requestId,
            request.getMethod(),
            request.getRequestURI(),
            response.getStatus(),
            duration);
      }
    }
  }

  /**
   * 获取客户端真实IP地址
   */
  private String getClientIpAddress(HttpServletRequest request) {
    String xForwardedFor = request.getHeader("X-Forwarded-For");
    if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
      return xForwardedFor.split(",")[0];
    }

    String xRealIp = request.getHeader("X-Real-IP");
    if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
      return xRealIp;
    }

    return request.getRemoteAddr();
  }

  /**
   * 生成请求ID
   */
  private String generateRequestId() {
    return "HTTP_" + System.currentTimeMillis() + "_" + Thread.currentThread().getId();
  }
}